namespace Spotted.Storage.Queues.Pages
{
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Controls.Primitives;
    using Microsoft.WindowsAzure.Samples.Phone.Storage;
    using Spotted.Storage.Queues.ViewModels;

    public partial class ListQueuesPage
    {
        public ListQueuesPage()
        {
            InitializeComponent();
            this.ViewModel = new ListQueuesPageViewModel();
        }

        public ListQueuesPageViewModel ViewModel
        {
            get { return this.DataContext as ListQueuesPageViewModel; }
            set { this.DataContext = value; }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            this.OnListQueues(this, null);
        }

        private void OnDeleteQueue(object sender, EventArgs e)
        {
            var queue = ((Button)sender).Tag as ICloudQueue;
            if (queue != null)
                this.ViewModel.DeleteQueue(queue);
        }

        private void OnListQueues(object sender, RoutedEventArgs e)
        {
            this.ViewModel.ListQueues();
        }

        private void OnQueueSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selector = (Selector)sender;
            if (selector.SelectedIndex != -1)
            {
                var queue = this.ViewModel.CloudQueues[selector.SelectedIndex];

                this.NavigationService.Navigate(
                    new Uri(string.Concat("/Storage/Queues/Pages/QueueDetailsPage.xaml?currentQueueName=", queue.Name), UriKind.Relative));
                selector.SelectedIndex = -1;
            }
        }

        private void OnNewQueue(object sender, EventArgs e)
        {
            this.ViewModel.NewQueue();
        }
    }
}